/**
 * Created by Simon on 2017/4/17.
 */

let sqlite3 = require('sqlite3').verbose();
let Banner = require('../../model/kingland-banner-model');
let db = new sqlite3.Database('./database/king-land.db');

function getAllBanners (callback) {
  let banners = [];
  db.serialize(function () {
    db.each(`SELECT * FROM KINGLAND_HOME_BANNER`, function (err, b) {
      banners.push(new Banner(b.id, b.name, b.image_url, b.status, b.update_time, b.sort_number));
    }, function () {
      callback(banners);
    });
  });
}

function getAllActiveBanners (callback) {
  let banners = [];
  db.serialize(function () {
    db.each(`SELECT * FROM KINGLAND_HOME_BANNER where status = 1`, function (err, b) {
      banners.push(new Banner(b.id, b.name, b.image_url, b.status, b.update_time, b.sort_number));
    }, function () {
      callback(banners);
    });
  });
}

function getBannerById (id, callback) {
  let banner = {};
  db.serialize(function () {
    db.each(`SELECT * FROM KINGLAND_HOME_BANNER where id = ${id}`, function (err, b) {
      banner = new Banner(b.id, b.name, b.image_url, b.status, b.update_time, b.sort_number);
    }, function () {
      callback(banner);
    });
  });
}

function saveOrUpdate (banner, callback) {
  db.serialize(function () {
    let insertSql  = `
      insert into kingland_home_banner values (
        $id,
        $name,
        $imageUrl,
        $status,
        datetime('now', '+8 hour'),
        $sortNumber
      )
    `;
    let updateSql = `
      update kingland_home_banner set
       name = $name,
       image_url = $imageUrl,
       update_time = datetime('now', '+8 hour'),
       status = $status,
       sort_number = $sortNumber
       where id = $id
    `;
    let prepareStmt = null;
    if(banner.id) {
      prepareStmt = db.prepare(updateSql);
    } else {
      prepareStmt = db.prepare(insertSql);
    }
    prepareStmt.run({
      $id: banner.id || null,
      $name: banner.name,
      $imageUrl: banner.imageUrl,
      $status: banner.status,
      $sortNumber: banner.sortNumber
    });
    prepareStmt.finalize();
  });
};

function deleteById (id, callback) {
  db.serialize(function () {
    db.run(`delete from kingland_home_banner where id = ?`, [id], callback);
  });
}

module.exports = {
  getAllBanners: getAllBanners,
  getAllActiveBanners: getAllActiveBanners,
  getBannerById: getBannerById,
  saveOrUpdate: saveOrUpdate,
  deleteById: deleteById
};